package easycloud.ecs.service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import easycloud.ecs.api.IProvider;

public final class ETagService {

	private static final Log logger = LogFactory.getLog(ETagService.class);

	private static final ETagService instance = new ETagService();

	public static ETagService getInstance() {
		return ETagService.instance;
	}

	private Map<IProvider, Map<String, String>> syncETags;

	private ETagService() {
		syncETags = new ConcurrentHashMap<IProvider, Map<String, String>>();
	}

	public Map<IProvider, Map<String, String>> getETags() {
		return syncETags;
	}

	public boolean isETagDiff(IProvider provider, File file, String eTag) {
		Map<String, String> etags = syncETags.get(provider);
		if (etags == null) {
			etags = new HashMap<String, String>();
			syncETags.put(provider, etags);
		}
		String localETag = etags.get(file.getAbsolutePath());
		if (!eTag.equals(localETag)) {
			return true;
		} else {
			return false;
		}
	}

	public void loadETags(Map<IProvider, Map<String, String>> eTags) {
		syncETags = eTags;

	}

	public void updateETag(IProvider provider, File file, String eTag) {
		logger.debug("updateETag : " + provider.getName() + " "
				+ file.getName() + " " + eTag);
		Map<String, String> etags = syncETags.get(provider);
		if (etags == null) {
			etags = new HashMap<String, String>();
			syncETags.put(provider, etags);
		}
		if (eTag != null) {
			etags.put(file.getAbsolutePath(), eTag);
		} else {
			etags.remove(file.getAbsolutePath());
		}
	}

	public void removeETags(IProvider provider, File dir) {
		logger.debug("removeETags : " + provider.getName() + " "
				+ dir.getName());
		Map<String, String> etags = syncETags.get(provider);
		List<String> removeKeys = new ArrayList<String>();
		for (Entry<String, String> entry : etags.entrySet()) {
			if (entry.getKey().startsWith(dir.getAbsolutePath())) {
				removeKeys.add(entry.getKey());
			}
		}
		for (String key : removeKeys) {
			etags.remove(key);
		}
	}

}
